import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import {Decrypt,Encrypt} from '@/utils/cryptojs'
import { JSEncrypt } from 'jsencrypt/bin/jsencrypt'
import md5 from 'js-md5'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    let publicKey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCbz6qrfWm4+XPNgKei0avUNuxiMvkF0mykREzblQHkzeh0DojHqmONVKLf+K6YExqh+7t6j+8Qr/g5r1+jUBoe0z0zg99wG0/alq6aJhZDjyymZnc58+RUjCkMZ46FWYA2kaM/KbRXETsN32iHBmETQafKED2ZJapHfXJKXPDdwIDAQAB'
    const data=config.data

    console.log(config)
    var jsencrypt = new JSEncrypt();
    jsencrypt.setPublicKey(publicKey);
    const decryptKey=jsencrypt.encrypt(md5(JSON.stringify(data)));

    const param={
      'a':Encrypt(JSON.stringify(data),'1234567890123456','1234567890123456')
    }
    config.data=JSON.stringify(param)

    config.headers['Content-Type']='application/json;charset=UTF-8'
    config.headers['decrypt']=decryptKey
    if (getToken() !== '') {
      config.headers['safe_level']='high'
      config.headers['authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response
    const responseData=res.data
    const md5Resp=res.headers.encrypt;
    const responseString=Decrypt(responseData,'9876543211234561','9876543211234561')
    const md5RespCal=md5(responseData)
    if(md5Resp!=md5RespCal){
      Message({
        message: "返回数据签名不匹配",
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject('error')
    }
    console.log(responseString)
    res.data=JSON.parse(responseString)
    console.log(res.status)
    if (res.status !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      if (res.code === 400 || res.code === 401 || res.code === 402) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出',
          { confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      const result=res.data
      console.log(result)
      if(result.code=='0000'){
        return response.data
      }else if (result.code == '400' || result.code == '401' || result.code == '402') {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出',
          { confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        return Promise.reject('error')
      }else{
        Message({
          message: result.msg,
          type: 'warning',
          duration: 1500
        })
        return response.data
      }
    }
  },
  error => {
    console.log('err' + error) // for debug
    const errorResponse=error.response
    if (errorResponse.status === 401 || errorResponse.status === 402) {
      MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
      return Promise.reject('error')
    }else if(errorResponse.status===403){
      Message({
        message: "无法访问",
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
